<script setup lang="ts">
  import { computed, nextTick, ref } from 'vue'
  import SvgIcon from '@/components/SvgIcon/index.vue'
  import { feedback, getConversationHistory, getHomeChat } from '@/api/agent'
  import { getThinkContent } from '@/views/Build/utils'
  import { Typewriter } from 'vue-element-plus-x'
  import { NIcon, useMessage } from 'naive-ui'
  import { KeyboardArrowUpOutlined, KeyboardArrowDownOutlined } from '@vicons/material'
  import { useAgent } from '@/hooks/useAgent'
  import { copyToClip } from '@/utils/copy'
  const { userName } = useAgent()
  const props = defineProps<{
    newConversationId?: string
  }>()

  const messageTitle = ref('')
  const rename = (item: { name: string; id: string }) => {
    if (curConversationId.value === item.id) {
      messageTitle.value = item.name
    }
  }

  const getHistory = async (item: { name: string; id: string }) => {
    messageTitle.value = item.name
    curConversationId.value = item.id
    const res = await getConversationHistory({
      conversation_id: item.id,
      limit: 30,
      name: userName,
    })
    generateHistory(res)
  }

  const generateHistory = (res: any) => {
    dialogList.value = []
    res.forEach((item: any) => {
      const userMessage = createUserMessage(item.query)
      userMessage.id = item.parent_message_id
      dialogList.value.push(userMessage)
      const aiMessage = createAIMessage(userMessage.id, false)
      aiMessage.loading = false
      aiMessage.id = item.id
      aiMessage.content = item.answer
      const think = getThinkContent(item.answer)
      aiMessage.think = think ?? ''
      if (think) {
        aiMessage.showThink = true
        aiMessage.content = item.answer
          .replace(think, '')
          .replace('</think>', '')
          .replace('<think>', '')
      } else {
        aiMessage.content = item.answer
      }
      dialogList.value.push(aiMessage)
    })
    fixIndex.value = dialogList.value.length - 1
  }
  // 创建用户消息对象
  const createUserMessage = (message: string, fileList?: any[]) => {
    const uuid = new Date().getTime()
    return {
      id: uuid,
      content: message,
      isUser: true,
      type: 'text',
      isLoading: false,
      conversationId: curConversationId.value ?? undefined,
      fileList: fileList ?? [],
    }
  }

  const curConversationId = ref('')
  // 创建AI回复消息对象
  const createAIMessage = (uuid: number, loading: boolean = true): any => {
    return {
      id: uuid + 1,
      content: '',
      isUser: false,
      type: 'text',
      isLoading: loading,
      isHistory: !loading,
      conversationId: curConversationId.value ?? undefined,
    }
  }

  const title = computed(() => {
    // 新对话则是第一条内容，历史对话则是历史对话标题
    return (
      messageTitle.value || (dialogList.value.length > 0 ? dialogList.value[0].content : '新对话')
    )
  })

  const emit = defineEmits(['createDialog'])
  const isSending = ref(false)
  const dialogList = ref<any[]>([])
  const fixIndex = ref(-1)
  const isNew = ref(false)
  const handleSend = async (message: string, fileList?: any[]) => {
    isSending.value = true
    // 创建并添加用户消息
    const userMessage = createUserMessage(message, fileList)
    if (dialogList.value.length === 0) {
      isNew.value = true
    } else {
      isNew.value = false
    }
    dialogList.value.push(userMessage)
    const files = fileList?.map(item => {
      return {
        url: item.url,
        transfer_method: 'local_file',
      }
    })
    const inputs = {
      file_path: files?.[0]?.url,
    }
    // 创建并添加AI回复消息
    const aiMessage = createAIMessage(userMessage.id)
    dialogList.value.push(aiMessage)
    fixIndex.value = dialogList.value.length - 1
    const res = await getHomeChat({
      query: message,
      userName,
      responseMode: 'blocking',
      conversationId: curConversationId.value ?? undefined,
      inputs,
    }).finally(() => {
      dialogList.value[fixIndex.value].isLoading = false
      isSending.value = false
      if (isNew.value) {
        emit('createDialog', {
          id: curConversationId.value,
          lastId: props.newConversationId,
          name: message.trim(),
        })
      }
    })

    const { answer, conversationId, timeConsuming, messageId } = res
    if (messageId) dialogList.value[fixIndex.value].id = messageId
    const think = getThinkContent(answer)
    dialogList.value[fixIndex.value].think = think ?? ''
    if (think) {
      dialogList.value[fixIndex.value].showThink = true
      dialogList.value[fixIndex.value].content = answer
        .replace(think, '')
        .replace('</think>', '')
        .replace('<think>', '')
    } else {
      dialogList.value[fixIndex.value].content = answer
    }
    curConversationId.value = conversationId
    dialogList.value[fixIndex.value].conversationId = conversationId
    dialogList.value[fixIndex.value].timeConsuming = timeConsuming
  }

  const message = useMessage()
  const handleCopy = async (content: string) => {
    if (navigator.clipboard) {
      await navigator.clipboard.writeText(content.trim())
      message.success('复制成功')
    } else {
      await copyToClip(content)
      message.success('复制成功')
    }
  }

  const handleFeedback = async (item: any, type: string) => {
    await feedback({
      messageId: item.id,
      rating: type,
      user: userName,
    })
    item.feedback = type
    message.success(`${type === 'like' ? '点赞成功' : '点踩成功'}`)
  }

  const containerRef = ref()
  /**
   * 滚动到聊天窗口底部
   */
  const scrollToBottom = async () => {
    await nextTick(() => {
      if (containerRef.value) {
        containerRef.value.scrollTop = containerRef.value.scrollHeight
      }
    })
  }

  defineExpose({ isSending, handleSend, rename, getHistory })
</script>

<template>
  <div class="h-full pingfang">
    <div class="h-[46px] leading-[46px] text-[14px] font-bold text-center">{{ title }}</div>
    <div class="h-[calc(100%-46px)] overflow-y-auto p-4 w-[900px] mx-auto" ref="containerRef">
      <div
        class="flex mb-8"
        :class="{ 'justify-end': item.isUser }"
        v-for="item in dialogList"
        :key="item.id"
      >
        <!-- 回答 -->
        <div v-if="!item.isUser" class="flex gap-4">
          <SvgIcon name="icon-agent" class="text-[32px]" />
          <div v-if="!item.isLoading">
            <!-- 思考 -->
            <div
              v-if="item.think"
              @click="item.showThink = !item.showThink"
              class="h-8 leading-8 flex items-center gap-1 text-[12px] px-4 bg-[#F6F6F6] rounded-lg w-fit"
            >
              <SvgIcon name="flower" class="text-[16px] flex items-center" />
              <span>已深度思考（用时{{ item.timeConsuming ?? 0 }}秒）</span>
              <n-icon class="cursor-pointer">
                <KeyboardArrowUpOutlined v-if="item.showThink" />
                <KeyboardArrowDownOutlined v-else />
              </n-icon>
            </div>
            <div
              v-if="item.think"
              v-show="item.showThink"
              class="text-[14px] mt-4 text-[#4A5055] px-3 leading-[22px] border-l border-l-[#F0F0F0]"
            >
              {{ item.think }}
            </div>
            <div v-if="item.type === 'text'" class="leading-7 text-[16px] mt-1">
              <Typewriter
                @writing="scrollToBottom"
                :content="item.content"
                :is-markdown="true"
                :typing="!item.isHistory"
              />
            </div>
            <div class="mt-3 flex item-center gap-2 text-[#4A5055]">
              <SvgIcon
                @click="handleCopy(item.content)"
                name="copy"
                class="text-[24px] cursor-pointer"
              />
              <SvgIcon
                @click="handleFeedback(item, 'like')"
                name="like"
                class="text-[24px] cursor-pointer"
              />
              <SvgIcon
                @click="handleFeedback(item, 'dislike')"
                name="unlike"
                class="text-[24px] cursor-pointer"
              />
            </div>
          </div>
          <!-- 思考中 -->
          <div v-else class="h-8 leading-8 text-[12px] flex items-center gap-1 px-4">
            <SvgIcon name="flower" class="text-[16px] flex items-center icon-spin" />
            <div>思考中</div>
            <SvgIcon name="loading" />
          </div>
        </div>
        <!-- 用户 -->
        <div v-else>
          <div class="flex items-center gap-4">
            <div v-if="item.type === 'text'" class="user-content leading-6">
              <div class="leading-6 text-[16px]">{{ item.content }}</div>
            </div>
            <SvgIcon name="icon-user" class="text-[32px]" />
          </div>
          <div class="mt-3 flex item-center gap-2 text-[#4A5055]">
            <SvgIcon
              @click="handleCopy(item.content)"
              name="copy"
              class="text-[24px] cursor-pointer"
            />
            <!-- <SvgIcon @click="handleFeedback(item, 'like')" name="like" class="text-[24px] cursor-pointer" />
              <SvgIcon @click="handleFeedback(item, 'dislike')" name="unlike" class="text-[24px] cursor-pointer" /> -->
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
